package com.jxb.demo.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc netty client处理器
 */
public class NettyClientHandler extends SimpleChannelInboundHandler {

    private static Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

    /**
     * @desc 读写数据处理
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        logger.info("msg:{}",msg.toString());
    }

    /**
     * @desc 客户端建立连接的处理
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("##########client is connect");
        for(int i=0;i<10;i++){
            Msg msg = new Msg();
            msg.setUserName("user-"+i);
            msg.setMsgTime(System.currentTimeMillis());
            msg.setMsgInfo("你好，2021。。。");
            msg.setMsgId("msgId-"+i);
            ctx.writeAndFlush(msg);
            System.out.println("client send object:"+msg);
        }

    }

    /**
     * @desc 连接关闭
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    /**
     * @desc 读取数据完成
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    /**
     * @desc 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
